package com.ruoyi.mes.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mes.domain.*;
import com.ruoyi.mes.mapper.*;
import com.ruoyi.mes.utils.AvgUtils;
import com.ruoyi.mes.utils.FourMechanicalArmUtils;
import com.ruoyi.mes.utils.MarkingMachineUtils;
import com.ruoyi.mes.utils.SixMechanicalArmUtils;
import com.ruoyi.mes.vo.plan.TaskCartVo;
import com.ruoyi.mes.vo.product.BomMtrVo;
import com.ruoyi.mes.vo.product.ProceVo;
import com.ruoyi.mes.vo.product.TecProceVo;
import com.ruoyi.mes.vo.wksp.RptVo;
//import javafx.concurrent.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mes.service.ITaskCartService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.core.domain.AjaxResult.DATA_TAG;

/**
 * 车间任务卡Service业务层处理
 *
 * @author LongAndHao
 * @date 2023-04-04
 */
@Service
public class TaskCartServiceImpl implements ITaskCartService {
    @Autowired
    private ProInfoServiceImpl proInfoService;

    @Autowired
    private TaskCartMapper taskCartMapper;

    @Autowired
    private WkspTaskMapper wkspTaskMapper;

    @Autowired
    private ProgPlanDetailMapper progPlanDetailMapper;

    @Autowired
    private ProgPlanMapper progPlanMapper;

    @Autowired
    private FinishInhouMapper finishInhouMapper;


    /**
     * 查询车间任务卡
     *
     * @param taskCardId 车间任务卡主键
     * @return 车间任务卡
     */
    @Override
    public TaskCart selectTaskCartByTaskCardId(Long taskCardId) {
        return taskCartMapper.selectTaskCartByTaskCardId(taskCardId);
    }

    /**
     * 查询车间任务卡列表
     *
     * @param taskCart 车间任务卡
     * @return 车间任务卡
     */
    @Override
    public List<TaskCart> selectTaskCartList(TaskCart taskCart) {
        return taskCartMapper.selectTaskCartList(taskCart);
    }

    /**
     * 新增车间任务卡
     *
     * @param taskCart 车间任务卡
     * @return 结果
     */
    @Override
    public int insertTaskCart(TaskCart taskCart) {
        taskCart.setCreateTime(DateUtils.getNowDate());
        return taskCartMapper.insertTaskCart(taskCart);
    }

    /**
     * 修改车间任务卡
     *
     * @param taskCart 车间任务卡
     * @return 结果
     */
    @Override
    public int updateTaskCart(TaskCart taskCart) {
        taskCart.setUpdateTime(DateUtils.getNowDate());
        return taskCartMapper.updateTaskCart(taskCart);
    }

    /**
     * 批量删除车间任务卡
     *
     * @param taskCardIds 需要删除的车间任务卡主键
     * @return 结果
     */
    @Override
    public int deleteTaskCartByTaskCardIds(Long[] taskCardIds) {
        return taskCartMapper.deleteTaskCartByTaskCardIds(taskCardIds);
    }

    /**
     * 删除车间任务卡信息
     *
     * @param taskCardId 车间任务卡主键
     * @return 结果
     */
    @Override
    public int deleteTaskCartByTaskCardId(Long taskCardId) {
        return taskCartMapper.deleteTaskCartByTaskCardId(taskCardId);
    }


    /**
     * 查 - 任务卡详情
     *
     * @param id 任务卡id
     * @return
     */
    @Override
    public AjaxResult getDetail(Long id) {
        TaskCart taskCart = taskCartMapper.selectTaskCartByTaskCardId(id);
        TaskCartVo taskCartVo = new TaskCartVo();
        taskCartVo.setTakCardCode(taskCart.getTakCardCode());

        List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByCode(taskCart.getTakCardCode());
        taskCartVo.setTaskCartPlanQuantity((long) taskCarts.size());

        //查询车间任务
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(taskCart.getWkspTaskId());
        taskCartVo.setWkspCode(wkspTask.getWkspCode());
        taskCartVo.setWkspTaskProductionSchedule((float) wkspTask.getWkspReadyQuantity() / wkspTask.getWkspPlanQuantity() * 100);
        //查询产品
        ProInfo proInfo = proInfoService.selectProInfoById(wkspTask.getProId());
        taskCartVo.setProCode(proInfo.getProCode());
        taskCartVo.setProName(proInfo.getProName());
        //查询Bom
        BomMtrVo bomMtrVo = proInfoService.getBomAndMtrByProId(wkspTask.getProId()).getData();
        taskCartVo.setBomMtrVo(bomMtrVo);
        //查询产品订单编码
        ProgPlanDetail progPlanDetail = progPlanDetailMapper.selectProgPlanDetailById(wkspTask.getProgDetailId());
        ProgPlan progPlan = progPlanMapper.selectProgPlanById(progPlanDetail.getProgId());
        taskCartVo.setOrderNumber(progPlan.getOrderNumber());

        return AjaxResult.success("查询成功!", taskCartVo);
    }


    /**
     * 查 - 已排序的工序
     *
     * @param id 任务卡id
     * @return
     */
    @Override
    public AjaxResult sorted(Long id) {
        TaskCart taskCart = taskCartMapper.selectTaskCartByTaskCardId(id);

        //查找工序
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(taskCart.getWkspTaskId());
        List<ProceInfo> proceInfos = proInfoService.getProTec(wkspTask.getProId()).getData().getProceInfos();
        proceInfos.sort(Comparator.comparing(ProceInfo::getProceSeque));//根据工序顺序排序

        //处理返回
        List<ProceVo> list = new ArrayList<>();
        for (ProceInfo proceInfo : proceInfos) {
            ProceVo proceVo = new ProceVo();
            BeanUtils.copyProperties(proceInfo, proceVo);
            list.add(proceVo);
        }

        return AjaxResult.success("查询成功!", list);
    }


    /**
     * 报工
     *
     * @param rptVo
     * @return
     */
    @Override
    @Transactional
    public AjaxResult report(RptVo rptVo) {
        TaskCart taskCart = taskCartMapper.selectTaskCartByTaskCardId(rptVo.getId());
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(taskCart.getWkspTaskId());

        List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByTaskCardCode(taskCart.getTakCardCode(), rptVo.getProceSeque() - 1, rptVo.getProductionQuantity());

        for (int i = 0; i < rptVo.getProductionQuantity(); i++) {

            //判断能否报工，差值为1才能报工，否报错
            if (Math.abs(taskCarts.get(i).getRptProceSeque() - rptVo.getProceSeque()) != 1) {
                return AjaxResult.error("前一步工序未完成!");
            }
            //能报工:已报工次数+1,更新已报工顺序
            taskCarts.get(i).setRptProceSeque(rptVo.getProceSeque());
            taskCarts.get(i).setTaskReadyRptNum(taskCarts.get(i).getTaskReadyRptNum() + 1);
            taskCartMapper.updateTaskCart(taskCarts.get(i));


            //**************************后续建议这些工具类的调用，根据实际情况扩展和调用
            //判断是否是六轴机械臂运作
            SixMechanicalArmUtils.SixMechanicalArmGrab(rptVo.getProceName());
            //判断是否是打标机运作
            MarkingMachineUtils.MarkingMachineMarkingWord(rptVo.getProceName());
            //判断是否是四轴机械臂运作
            FourMechanicalArmUtils.FourMechanicalArmMove(rptVo.getProceName());

            //判断是否已完工 ：需报工次数 == 已报工次数
            //若已完工，改变任务卡状态,车间任务已生产数量+1
            //若车间任务 计划生产数量 == 已生产数量 更新车间任务状态  新增产品入库记录

            List<TaskCart> list = taskCartMapper.selectTaskCartByCode(taskCart.getTakCardCode());
            //计算需报工次数，及已报工次数总和
            int needCount = 0, readyCount = 0;
            for (TaskCart cart : taskCarts) {
                needCount += cart.getTaskNeedRptNum();
                readyCount += cart.getTaskReadyRptNum();
            }

            if (needCount == readyCount) {
                //修改状态
                for (TaskCart cart : taskCarts) {
                    cart.setStatus(2L);//已完工
                    taskCartMapper.updateTaskCart(cart);
                }

                wkspTask.setWkspReadyQuantity((long) taskCarts.size() + wkspTask.getWkspReadyQuantity());
                wkspTaskMapper.updateWkspTask(wkspTask);
                if (wkspTask.getWkspPlanQuantity().longValue() == wkspTask.getWkspReadyQuantity().longValue()) {
                    wkspTask.setOperationStatus(2L);

                    //新增产品入库记录
                    FinishInhou finishInhou = new FinishInhou();
                    finishInhou.setWkspTaskId(wkspTask.getId());
                    finishInhou.setWkspCode(wkspTask.getWkspCode());
                    finishInhou.setProId(wkspTask.getProId());
                    finishInhou.setInhouName(SecurityUtils.getLoginUser().getUser().getNickName());
                    finishInhou.setInhouTime(DateUtils.getNowDate());
                    finishInhou.setInhouQuantity(wkspTask.getWkspReadyQuantity());
                    finishInhou.setStatus(0l);//默认未入库
                    finishInhou.setRemark("测试数据");
                    finishInhouMapper.insertFinishInhou(finishInhou);
                }

                wkspTaskMapper.updateWkspTask(wkspTask);

                return AjaxResult.success("任务卡已完工!");
            }
        }

        try {
            Thread.sleep(1000 * 60); // 休眠一分钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //派遣小车
        AvgUtils.DispatchAvg();

        return AjaxResult.success("报工成功!");
    }

    /**
     * 查 - 任务卡分页 - 任务卡编码不重复
     *
     * @param taskCart
     * @return
     */
    @Override
    public List<TaskCart> taskCardList(TaskCart taskCart) {
        List<TaskCart> taskCarts = taskCartMapper.taskCardList(taskCart);
        if (taskCarts.size() != 0) {

            for (TaskCart cart : taskCarts) {
                boolean flag = false;

                //计算需报工次数，已报工次数总和
                List<TaskCart> list = taskCartMapper.selectTaskCartByCode(cart.getTakCardCode());
                int needCount = 0, readyCount = 0;
                for (TaskCart cart1 : list) {
                    needCount += cart1.getTaskNeedRptNum();
                    readyCount += cart1.getTaskReadyRptNum();
                    if (cart1.getStatus() == 1) {
                        flag = true;
                    }

                }

                WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(cart.getWkspTaskId());
                cart.setWkspCode(wkspTask.getWkspCode());
                cart.setTaskCartProductionSchedule((float) readyCount / needCount * 100);
                if (flag) {
                    cart.setStatus(1L);
                }
                ProInfo proInfo = proInfoService.selectProInfoById(wkspTask.getProId());
                cart.setProCode(proInfo.getProCode());
                cart.setProName(proInfo.getProName());


            }
        }
        return taskCarts;
    }

    /**
     * 查 - 可报工数量
     *
     * @param id         任务卡id
     * @param proceSeque 报工顺序
     * @return
     */
    @Override
    public AjaxResult getTransferredQuantity(Long id, Long proceSeque) {
        TaskCart taskCart = taskCartMapper.selectTaskCartByTaskCardId(id);
        List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByTaskCardCode(taskCart.getTakCardCode(), proceSeque - 1, -1);
        return AjaxResult.success("可报工数量", taskCarts.size());
    }
}
